package com.xmut.bs.handaccount.base;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.Toast;

import com.readystatesoftware.systembartint.SystemBarTintManager;
import com.xmut.bs.handaccount.R;
import com.xmut.bs.handaccount.util.DisplayUtils;
import com.xmut.bs.handaccount.util.RoundCornersTransformation;
import com.xmut.bs.handaccount.util.StringUtil;
import com.xmut.bs.handaccount.util.swipeback.app.SwipeBackActivity;

import butterknife.ButterKnife;
import cn.bingoogolapple.refreshlayout.BGANormalRefreshViewHolder;
import cn.bingoogolapple.refreshlayout.BGARefreshLayout;

/**
 * Activity 基类
 * Author Dollkey
 * Date 2017/8/7 9:55.
 */

public abstract class BaseActivity extends SwipeBackActivity {

    /**
     * 日志输出标志
     **/
    protected final String TAG = this.getClass().getSimpleName();

    /**
     * this实例
     */
    protected Context mContext;
    private SystemBarTintManager tintManager;
    private Window window;

    protected float mDensity;
    protected int mDensityDpi;
    protected int mWidth;
    protected int mHeight;

    public RoundCornersTransformation mRoundCornersTransformation;

    public int colorPrimary;


    /**
     * 获取布局ID
     *
     * @return 布局id
     */
    protected abstract int bindLayoutId();

    /**
     * 字体库
     */
    public Typeface iconfont;

    /**
     * 初始化布局以及View控件
     */
    protected abstract void initView(Bundle savedInstanceState);

    /**
     * 界面初始化前期准备
     */
    protected void beforeInit() {
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        BaseApplication.getInstance().addActivity(this);
        initSystemBarTint();
        mContext = this;
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        mDensity = dm.density;
        mDensityDpi = dm.densityDpi;
        mWidth = dm.widthPixels;
        mHeight = dm.heightPixels;
        mRoundCornersTransformation = new RoundCornersTransformation(mContext,
                DisplayUtils.dp2px(mContext, 4), RoundCornersTransformation.CornerType.ALL);

        if (!isAllowScreenRotate()) {
            //        handler = new ChangeOrientationHandler(this);
            //        sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
            //        sensor = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
            //        listener = new OrientationSensorListener(handler);
            //        sm.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_UI);
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }
        if (!mAllowFullScreen() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            requestWindowFeature(Window.FEATURE_NO_TITLE);
        }
        if (isShapeIcon()) {
            iconfont = Typeface.createFromAsset(getAssets(), "iconfont.ttf");
        }
        Log.d(TAG, "BaseActivity-->onCreate()");
        initParams(getIntent());
        beforeInit();
        if (bindLayoutId() != 0) {
            setContentView(bindLayoutId());
            colorPrimary = getResources().getColor(R.color.colorPrimary);
            ButterKnife.bind(this);
            initView(savedInstanceState);
        }
    }

    /**
     * 初始化参数
     *
     * @param intent
     */
    protected abstract void initParams(Intent intent);

    /**
     * 设置状态栏颜色
     */
    protected void initSystemBarTint() {
        window = getWindow();
        if (translucentStatusBar()) {
            // 设置状态栏全透明
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
                window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                window.setStatusBarColor(Color.TRANSPARENT);
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            }
            return;
        }
        // 沉浸式状态栏
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            //5.0以上使用原生方法
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(setStatusBarColor());
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //4.4-5.0使用三方工具类，有些4.4的手机有问题，这里为演示方便，不使用沉浸式
            //                        window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            tintManager = new SystemBarTintManager(this);
            tintManager.setStatusBarTintEnabled(true);
            tintManager.setStatusBarTintColor(setStatusBarColor());
        }
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);

        if (hasFocus && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && !isShowNavigation()) {
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
        }
    }

    /**
     * 是否状态栏全透明
     **/
    protected boolean translucentStatusBar() {
        return false;
    }

    /**
     * 是否允许全屏
     **/
    protected boolean mAllowFullScreen() {
        return true;
    }

    /**
     * 是否显示导航栏
     **/
    protected boolean isShowNavigation() {
        return true;
    }

    /**
     * 是否使用字体图片
     */
    protected boolean isShapeIcon() {
        return false;
    }

    /**
     * 是否允许旋转屏幕
     **/
    protected boolean isAllowScreenRotate() {
        return true;
    }

    /**
     * 子类可以重写改变状态栏颜色
     */
    protected int setStatusBarColor() {
        return getResources().getColor(R.color.colorPrimary);
    }

    /**
     * 带参数的页面跳转
     *
     * @param clz    跳转Activity
     * @param bundle 参数
     */
    public void startActivity(Class<?> clz, Bundle bundle) {
        Intent intent = new Intent();
        intent.setClass(this, clz);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
    }

    public void startActivity(Intent intent, Class<?> clz) {
        intent.setClass(this, clz);
        startActivity(intent);
    }

    public void startActivity(Class<?> clz) {
        startActivity(clz, null);
    }

    /**
     * 带返回值的页面跳转
     *
     * @param cls         跳转Activity
     * @param bundle      参数
     * @param requestCode 请求码
     */
    public void startActivityForResult(Class<?> cls, Bundle bundle,
                                       int requestCode) {
        Intent intent = new Intent();
        intent.setClass(this, cls);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivityForResult(intent, requestCode);
    }

    public void startActivityForResult(Class<?> cls, Intent intent,
                                       int requestCode) {
        intent.setClass(this, cls);
        startActivityForResult(intent, requestCode);
    }

    public void startActivityForResult(Class<?> cls,
                                       int requestCode) {
        startActivityForResult(cls, new Intent(), requestCode);
    }

    private Toast mToast;

    protected void showToast(String msg) {
        if (mToast == null) {
            mToast = Toast.makeText(this.getApplicationContext(), msg, Toast.LENGTH_SHORT);
        } else {
            mToast.setText(msg);
        }
        mToast.show();
    }

    public boolean checkEditText(EditText editText) {
        if (StringUtil.isNull(editText.getText().toString().trim())) {
            showToast(editText.getHint().toString().trim());
            return false;
        }
        return true;
    }

    public String getEditText(EditText editText) {
        return StringUtil.notNull(editText.getText().toString().trim());
    }

    public int getEditTextWithInt(EditText editText) {
        return Integer.parseInt(editText.getText().toString().trim());
    }

    @Override
    protected void onDestroy() {
        if (mToast != null)
            mToast.cancel();
        super.onDestroy();
    }

    public void initRefreshLayout(BGARefreshLayout refreshLayout, BGARefreshLayout.BGARefreshLayoutDelegate delegate) {
        // 为BGARefreshLayout 设置代理
        refreshLayout.setDelegate(delegate);
        // 设置下拉刷新和上拉加载更多的风格     参数1：应用程序上下文，参数2：是否具有上拉加载更多功能
        //        BGARefreshViewHolder refreshViewHolder = new XXXImplRefreshViewHolder(this, true);
        // 设置下拉刷新和上拉加载更多的风格
        BGANormalRefreshViewHolder refreshViewHolder = new BGANormalRefreshViewHolder(mContext, true);
        refreshLayout.setRefreshViewHolder(refreshViewHolder);

        // 为了增加下拉刷新头部和加载更多的通用性，提供了以下可选配置选项  -------------START
        // 设置正在加载更多时不显示加载更多控件
        refreshLayout.setIsShowLoadingMoreView(false);
        // 设置正在加载更多时的文本
        //        refreshViewHolder.setLoadingMoreText("加载更多");
        // 设置整个加载更多控件的背景颜色资源 id
        //        refreshViewHolder.setLoadMoreBackgroundColorRes(loadMoreBackgroundColorRes);
        // 设置整个加载更多控件的背景 drawable 资源 id
        //        refreshViewHolder.setLoadMoreBackgroundDrawableRes(loadMoreBackgroundDrawableRes);
        // 设置下拉刷新控件的背景颜色资源 id
        //        refreshViewHolder.setRefreshViewBackgroundColorRes(refreshViewBackgroundColorRes);
        // 设置下拉刷新控件的背景 drawable 资源 id
        //        refreshViewHolder.setRefreshViewBackgroundDrawableRes(refreshViewBackgroundDrawableRes);
        // 设置自定义头部视图（也可以不用设置）     参数1：自定义头部视图（例如广告位）， 参数2：上拉加载更多是否可用
        //        refreshLayout.setCustomHeaderView(mBanner, false);
        // 可选配置  -------------END
    }
}
